import 'package:ente_ui/components/buttons/button_widget.dart';
import 'package:ente_ui/components/buttons/models/button_type.dart';
import 'package:ente_ui/components/text_input_widget.dart';
import 'package:ente_ui/theme/ente_theme.dart';
import 'package:flutter/material.dart';
import 'package:locker/l10n/l10n.dart';
import 'package:locker/services/collections/collections_service.dart';
import 'package:locker/services/collections/models/collection.dart';
import 'package:locker/services/files/sync/models/file.dart';
import 'package:locker/ui/components/collection_selection_widget.dart';
import 'package:locker/utils/file_icon_utils.dart';
import 'package:locker/utils/snack_bar_utils.dart';

class FileEditDialogResult {
  final String title;
  final String caption;
  final List<Collection> selectedCollections;

  FileEditDialogResult({
    required this.title,
    required this.caption,
    required this.selectedCollections,
  });
}

class FileEditDialog extends StatefulWidget {
  final EnteFile file;
  final List<Collection> collections;

  const FileEditDialog({
    super.key,
    required this.file,
    required this.collections,
  });

  @override
  State<FileEditDialog> createState() => _FileEditDialogState();
}

class _FileEditDialogState extends State<FileEditDialog> {
  final TextEditingController _titleController = TextEditingController();
  final TextEditingController _captionController = TextEditingController();
  final Set<int> _selectedCollectionIds = <int>{};
  List<Collection> _availableCollections = [];

  @override
  void initState() {
    super.initState();

    _availableCollections = List.from(widget.collections);

    _titleController.text = widget.file.displayName;

    _captionController.text = widget.file.caption ?? '';

    CollectionService.instance
        .getCollectionsForFile(widget.file)
        .then((fileCollections) {
      for (final collection in fileCollections) {
        _selectedCollectionIds.add(collection.id);
      }
      setState(() {});
    });
  }

  @override
  void dispose() {
    _titleController.dispose();
    _captionController.dispose();
    super.dispose();
  }

  void _toggleCollection(int collectionId) {
    setState(() {
      if (_selectedCollectionIds.contains(collectionId)) {
        _selectedCollectionIds.remove(collectionId);
      } else {
        _selectedCollectionIds.add(collectionId);
      }
    });
  }

  void _onCollectionsUpdated(List<Collection> updatedCollections) {
    setState(() {
      _availableCollections = updatedCollections;
    });
  }

  Future<void> _onCancel() async {
    Navigator.of(context).pop();
  }

  Future<void> _onSave() async {
    final selectedCollections = _availableCollections
        .where((c) => _selectedCollectionIds.contains(c.id))
        .toList();

    if (selectedCollections.isEmpty) {
      SnackBarUtils.showWarningSnackBar(
        context,
        context.l10n.pleaseSelectAtLeastOneCollection,
      );
      return;
    }

    final result = FileEditDialogResult(
      title: _titleController.text.trim(),
      caption: _captionController.text.trim(),
      selectedCollections: selectedCollections,
    );

    Navigator.of(context).pop(result);
  }

  String get _fileName {
    return widget.file.displayName;
  }

  @override
  Widget build(BuildContext context) {
    final colorScheme = getEnteColorScheme(context);
    final textTheme = getEnteTextTheme(context);

    return Dialog(
      backgroundColor: colorScheme.backgroundElevated,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
      ),
      child: Container(
        width: 400,
        constraints: const BoxConstraints(maxHeight: 600),
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(
                  FileIconUtils.getFileIcon(_fileName),
                  color: FileIconUtils.getFileIconColor(_fileName),
                  size: 24,
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: Text(
                    _fileName,
                    style: textTheme.largeBold,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 20),
            Text(
              'Title',
              style: textTheme.small.copyWith(
                color: colorScheme.textBase,
              ),
            ),
            const SizedBox(height: 8),
            TextInputWidget(
              hintText: context.l10n.fileTitle,
              initialValue: _titleController.text,
              onChange: (value) => _titleController.text = value,
              maxLength: 200,
              textCapitalization: TextCapitalization.words,
            ),
            const SizedBox(height: 16),
            Text(
              context.l10n.note,
              style: textTheme.small.copyWith(
                color: colorScheme.textBase,
              ),
            ),
            const SizedBox(height: 8),
            TextInputWidget(
              hintText: context.l10n.optionalNote,
              initialValue: _captionController.text,
              onChange: (value) => _captionController.text = value,
              maxLength: 500,
              textCapitalization: TextCapitalization.sentences,
            ),
            const SizedBox(height: 16),
            CollectionSelectionWidget(
              collections: _availableCollections,
              selectedCollectionIds: _selectedCollectionIds,
              onToggleCollection: _toggleCollection,
              onCollectionsUpdated: _onCollectionsUpdated,
            ),
            const SizedBox(height: 20),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Flexible(
                  child: ButtonWidget(
                    buttonType: ButtonType.secondary,
                    labelText: context.l10n.cancel,
                    onTap: _onCancel,
                  ),
                ),
                const SizedBox(width: 12),
                Flexible(
                  child: ButtonWidget(
                    buttonType: ButtonType.primary,
                    labelText: context.l10n.save,
                    onTap: _onSave,
                    isDisabled: _selectedCollectionIds.isEmpty,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

Future<FileEditDialogResult?> showFileEditDialog(
  BuildContext context, {
  required EnteFile file,
  required List<Collection> collections,
}) async {
  return showDialog<FileEditDialogResult>(
    context: context,
    barrierColor: getEnteColorScheme(context).backdropBase,
    builder: (context) => FileEditDialog(
      file: file,
      collections: collections,
    ),
  );
}
